package com.dyz.swordFingerOffer;

import com.dyz.baseAlgorithm.queue.CircleQueue;

import java.util.ArrayList;
import java.util.Stack;

public class Convert36 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        TreeNode node1 = new TreeNode(6);
        TreeNode node2 = new TreeNode(8);
        TreeNode node3 = new TreeNode(4);
        TreeNode node4 = new TreeNode(12);
        TreeNode node5 = new TreeNode(14);
        TreeNode node6 = new TreeNode(16);
        node1.left = node3;
        node1.right = node2;
        node5.left = node4;
        node5.right = node6;
        root.left = node1;
        root.right = node5;

        TreeNode treeNode = new Convert36().Convert1(root);
        System.out.println(1);
//         new Convert36().InOrder(root);
    }
    public void InOrder(TreeNode node){
        if(node==null){
            return;
        }
        InOrder(node.left);
        System.out.println(node.val);
        InOrder(node.right);
    }
    public TreeNode Convert(TreeNode pRootOfTree) {
        //图中是树的中序遍历
        if (pRootOfTree==null){
            return null;
        }
        ArrayList<TreeNode> tmpList = new ArrayList<>();
        InOrder(pRootOfTree, tmpList);
        TreeNode head = tmpList.get(0);
        TreeNode ptr = head;
        head.left = null;
        for (int i =1; i<tmpList.size(); i++){
            ptr.right = tmpList.get(i);
            tmpList.get(i).left = ptr;
            ptr = ptr.right;
        }
        return head;
    }

    //中序递归遍历
    public void InOrder(TreeNode node, ArrayList<TreeNode> tmpList){
        if (node==null){
            return;
        }
        InOrder(node.left, tmpList);
        tmpList.add(node);
        InOrder(node.right,tmpList);
    }
    //解法2
    public TreeNode Convert1(TreeNode pRootOfTree) {
        if(pRootOfTree == null){
            return pRootOfTree;
        }

        Stack<TreeNode> stack = new Stack<>();
        TreeNode head = null;//用于返回链表的头结点
        TreeNode pre = null;//用于保存遍历过程中的前一个结点
        while (!stack.isEmpty() || pRootOfTree!=null){
            if(pRootOfTree!=null){
                stack.push(pRootOfTree);
                pRootOfTree = pRootOfTree.left;
            }else {
                pRootOfTree = stack.pop();
                if(head == null){
                    head = pRootOfTree;
                    pre = pRootOfTree;
                }else {
                    pre.right = pRootOfTree;
                    pRootOfTree.left = pre;
                    pre = pRootOfTree;
                }
                pRootOfTree = pRootOfTree.right;
            }

        }
        return head;
    }
}
